<style lang="less">
    
</style>

<template>
    <div>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
            <Row>
                <Col span="12">
                    <FormItem label="课程视频内容" prop="media_url" :label-width="100">
                        <div>
                            <Upload 
                            ref="uploadVideo"
                            :format="['mp4']"
                            :max-size="409600"
                            :on-format-error="handleVideoFormatError"
                            :on-exceeded-size="handleVideoMaxSize"
                            :on-success="handleVideoUploadSuccess"
                            :on-remove="handleRemoveVideo" 
                            :before-upload="handleBeforeUpload"
                            :headers= "headers" 
                            type="drag" 
                            :action="videoAction">
                                <div style="padding: 20px 0">
                                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                    <p>点击或将文件拖拽到这里上传</p>
                                </div>
                            </Upload>
                            <Input v-model="formValidate.media_url" v-show="false"></Input>
                        </div>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="课程名称" prop="name">
                        <Input v-model="formValidate.name" placeholder="请输入课程名称"></Input>
                    </FormItem>
                    <FormItem label="课程分类" prop="class_id">
                        <Select v-model="formValidate.class_id" placeholder="请选择课程分类">
                            <Option v-for="item in classList" :key="item.index" :value="item.id">{{ item.name }}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="可得学分" prop="points">
                        <Input v-model.number="formValidate.points" placeholder="请输入学习课程可得学分"></Input>
                    </FormItem>
                    <FormItem label="课程简介" prop="describe">
                        <Input v-model="formValidate.describe" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入课程介绍"></Input>
                    </FormItem>
                    <FormItem label="排序值" prop="listorder">
                        <Input v-model.number="formValidate.listorder" placeholder="请输入课程排序值"></Input>
                    </FormItem>
                    <FormItem label="课程首图" prop="headimg">
                        <div>
                            <Upload 
                            ref="upload"
                            :max-size="2048"
                            :format="['jpg','jpeg','png']"
                            :on-format-error="handleFormatError"
                            :on-exceeded-size="handleMaxSize"
                            :on-success="handleUploadSuccess"  
                            :on-remove="handleRemoveFile"  
                            :on-preview="handlePreview"  
                            :before-upload="handleBeforeUpload"
                            type="drag"
                            :headers= "headers"
                            :action="headimgAction" >
                                <div style="padding: 20px 0">
                                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                    <p>点击或将文件拖拽到这里上传</p>
                                </div>
                            </Upload>
                            <Input v-model="formValidate.headimg" v-show="false"</Input>
                        </div>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="handleSubmit('formValidate')" :disabled="isDisabled">提交</Button>
                        <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                    </FormItem>
                </col>
            </Row>
            <Modal title="预览图片" v-model="visible" class="preview">
                <img :src="pre_img_url" style="width: 100%">
                <div slot="footer"></div>
            </Modal>
        </Form>
    </div>
</template>

<script>
import http from '../../../libs/http';
import Cookies from 'js-cookie';
export default {
    data () {
        return {
            headimgAction: this.host + 'admin/course/uploadHeadImg',
            videoAction: this.host + 'admin/course/uploadVideo',
            isDisabled: false,
            classList: [],
            uploadList: [], //首图上传列表
            uploadVideoList: [],  //视频上传列表
            visible: false,
            pre_img_url: '',
            formValidate: {
                name: '',
                describe: '',
                class_id: '',
                points: '',
                listorder: '',
                headimg: '',
                media_url: '',
            },
            ruleValidate: {
                name: [
                    { required: true, message: '课程名不能为空', trigger: 'blur' }
                ],
                class_id: [
                    { required: true, message: '请选择课程分类', trigger: 'change', type: 'number' }
                ],
                describe: [
                    { required: true, message: '请输入课程简介', trigger: 'blur' },
                    { type: 'string', min: 1, message: '课程简介不能为空', trigger: 'blur' }
                ],
                points: [
                    { type:'number', required: true, message: '学习课程可得学分为空或格式错误', trigger: 'blur'},
                ],
                listorder: [
                    {type: 'number', message: '请输入数字', trigger: 'blur'}
                ],
                headimg: [
                    { required: true, message: '课程首图不能为空', trigger: 'blur'}
                ],
                media_url: [
                    { required: true, message: '课程视频不能为空', trigger: 'blur'}
                ]
            }
        }
    },
    methods: {
        handleSubmit (name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    //提交后台
                    var data = {
                        name: this.formValidate.name,
                        describe: this.formValidate.describe,
                        class_id: this.formValidate.class_id,
                        class_type: 1, //课程类型为视频
                        headimg: this.formValidate.headimg,
                        media_url:this.formValidate.media_url,
                        points: this.formValidate.points,
                        listorder: this.formValidate.listorder
                    }
                    this.apiPost('admin/course/save', data).then((res) => {
                        if (res.code != 200) {
                            this.handleError(res);
                        } else {
                            this.$Message.success('添加课程成功');
                            this.handleReset(name);  //清空表单内容
                            this.$refs.upload.clearFiles();
                            this.$refs.uploadVideo.clearFiles();
                            this.uploadVideoList = [];  //清空显示的上传列表
                            this.uploadList = []; //清空上传列表
                            this.$emit('addVideoCancel');
                        }
                    })
                } else {
                    this.$Message.error('表单验证失败!');
                }
            })
        },
        handleReset (name) {
            this.$refs[name].resetFields();
        },
        handleBeforeUpload () {  //上传前处理
            const check = this.uploadList.length < 1;
            const checkVideo = this.uploadVideoList.length < 1;
            if (!check) {
                this.$Notice.warning({
                    title: '每次仅能上传一张图片'
                });
            } else if (!checkVideo) {
                this.$Notice.warning({
                    title: '每次仅能上传一部视频'
                })
            } else {
                this.isDisabled = true;
            }
            return check;
        },
        handleFormatError (file) { //文件格式错误
            this.isDisabled = false;
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize (file) {   //文件过大
            this.isDisabled = false;
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        handleVideoFormatError (file) { //视频上传格式错误
            this.isDisabled = false;
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传MP4格式的视频。'
            });
        },
        handleVideoMaxSize(file) {   //视频过大
            this.isDisabled = false;
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 400M。'
            });
        },
        handleUploadSuccess (res, file) {   //首图上传成功
            if (res.code != 200) {
                this.handleError(res);
            } else {
                this.isDisabled = false;
                this.formValidate.headimg = res.data;
                file.url = res.data;
            }
        },
        handleVideoUploadSuccess (res, file) {  //视频上传成功
            if (res.code != 200) {
                this.handleError(res);
            } else {
                this.isDisabled = false;
                this.media_url = res.data;
                file.url = res.data;
            }
        },
        handleRemoveFile (file) {   //删除首图
            var data = { url: file.url }
            this.apiPost('admin/course/deleteFile', data).then((res) => {
            })
        },
        handleRemoveVideo (file) {   //删除视频
            var data = { url: file.url }
            this.apiPost('admin/course/deleteVideo', data).then((res) => {
            })
        },
        getClassCate() {  //获取课程分类
            var that = this
            this.apiGet('admin/classCate/index/type/1').then((res) => {
                if (res.code != 200) {
                    this.handleError(res);
                } else {             
                    that.classList = res.data.list;
                }
            })
        },
        handlePreview (file) {  //预览上传图片
            this.pre_img_url = file.url;
            this.visible = true;
        }
    },
    computed: {
        headers() {
            return {
                'authKey': Cookies.get('authKey'),
                'sessionId': Cookies.get('sessionId')
            }
        }
    },
    mounted () {
        this.uploadList = this.$refs.upload.fileList;
        this.uploadVideoList = this.$refs.uploadVideo.fileList;
    },
    mixins: [http]
}
</script>

